//
//  LoginViewController.m
//  shusheng
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "LoginViewController.h"
#import "SignUpViewController.h"
#import "CDCacheManager.h"
#import "CDChatManager.h"
#import "CDIMService.h"
#import "CDUserManager.h"


@interface LoginViewController ()<UITextFieldDelegate>
@property (strong,nonatomic) UIImageView *backgroundImg;

@property (strong,nonatomic) UIImageView *userImage;
@property (strong,nonatomic) UIImageView *lockImage;
@property (strong,nonatomic) UILabel     *userLabel;
@property (strong,nonatomic) UILabel     *pswLabel;
@property (strong,nonatomic) UIView      *userView;
@property (strong,nonatomic) UIView      *pswView;
@property (strong,nonatomic) UITextField *userNameTextField;
@property (strong,nonatomic) UITextField *passwordTextField;

@property (strong,nonatomic) UIButton *signInBtn; /**< 登录 */
@property (strong,nonatomic) UIButton *signUpBtn;  /**< 注册 */
@property (strong,nonatomic) UIButton *findPswBtn; /**< 忘记密码 */

- (void)initializeInterface;  //初始化用户界面
- (void)havedata;  /**< 判断是否保存了登录信息 */

//动画
- (void)beginAnimation;
- (void)userLabelClickAnimation;
- (void)passwordClickLabelAnimation;
- (void)userLabelCancelAnimation;
- (void)passwordCancelLabelAnimation;
@end

@implementation LoginViewController
- (void)dealloc {
    // 移除通知
    // ARC模式下无需调用[super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -- LifeCycle --

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    [self havedata];
    self.userNameTextField.delegate = self;
    self.passwordTextField.delegate = self;

}

-(void)initializeInterface{
//    self.view.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.backgroundImg];
    [self.view addSubview:self.userNameTextField];
    [self.view addSubview:self.userImage];
    [self.view addSubview:self.userLabel];
    [self.view addSubview:self.userView];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.lockImage];
    [self.view addSubview:self.pswLabel];
    [self.view addSubview:self.pswView];
    [self.view addSubview:self.signInBtn];
    [self.view addSubview:self.signUpBtn];
    [self.view addSubview:self.findPswBtn];
    [self beginAnimation];
}


#pragma mark -- action --
-(void)havedata{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"psw"]) {
        [self initializeInterface];
    }else{

        self.userNameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_USERNAME];
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"psw"];
        [self respondsToSignInButton];
    }

}


//登录
-(void)respondsToSignInButton{
    AVObject *testObject = [AVObject objectWithClassName:@"TestObject"];
    [testObject setObject:@"bar" forKey:@"foo"];
    [testObject save];
    [MBProgressHUD showMessage:@"登录中"];
    [[CDUserManager manager]loginWithInput:self.userNameTextField.text password:self.passwordTextField.text block:^(AVUser *user, NSError *error) {
        if (error == nil) {
            [MBProgressHUD showSuccess:@"登陆成功"];
            [[NSUserDefaults standardUserDefaults] setObject:self.userNameTextField.text forKey:KEY_USERNAME];
            [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"psw"];
            [UIApplication sharedApplication].keyWindow.rootViewController = [[MainViewController alloc]init];
            // 登录进入主页
            [[CDCacheManager manager] registerUsers:@[[AVUser currentUser]]];
            [CDChatManager manager].userDelegate = [CDIMService service];
            
            
#ifdef DEBUG
#warning 使用开发证书来推送，方便调试，具体可看这个变量的定义处
            [CDChatManager manager].useDevPushCerticate = YES;
#endif
            //聊天
            [[CDChatManager manager] openWithClientId:[AVUser currentUser].objectId callback: ^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                } else {
                    [MBProgressHUD showError:[error detialMessage]];
                }
            }];
        }else{
            [MBProgressHUD showError:error.detialMessage];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:KEY_USERNAME];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"psw"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//             [UIApplication sharedApplication].keyWindow.rootViewController = [[LoginViewController alloc]init];
        }
    }];
}

-(void)respondsToSignUpButton{
    SignUpViewController *signUpVc = [[SignUpViewController alloc]init];
    [self presentViewController:signUpVc animated:YES completion:nil];
}
#pragma mark -- animation

-(void)beginAnimation{
    [UIView animateWithDuration:0.3 delay:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
        _userView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.userNameTextField.frame));
    } completion:nil];
    [UIView animateWithDuration:0.3 delay:0.8 options:UIViewAnimationOptionCurveLinear animations:^{
        _userImage.alpha = 1;
    } completion:nil];
    [UIView animateWithDuration:0.3 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
        _userLabel.center = CGPointMake(CGRectGetMaxX(self.userImage.frame)+76, CGRectGetMidY(self.userImage.frame));
    } completion:nil];
    
    [UIView animateWithDuration:0.3 delay:0.7 options:UIViewAnimationOptionCurveLinear animations:^{
       _pswView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.passwordTextField.frame));
    } completion:nil];
    [UIView animateWithDuration:0.3 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
        _lockImage.alpha = 1;
    } completion:nil];
    [UIView animateWithDuration:0.3 delay:1.2 options:UIViewAnimationOptionCurveLinear animations:^{
        _pswLabel.center = CGPointMake(CGRectGetMaxX(self.lockImage.frame)+76, CGRectGetMidY(self.lockImage.frame));
    } completion:nil];
    [UIView animateWithDuration:0.3 delay:1.4 options:UIViewAnimationOptionCurveLinear animations:^{
        _signInBtn.alpha = 1;
        _signUpBtn.alpha = 1;
        _findPswBtn.alpha = 1;
    } completion:nil];
    
}

-(void)userLabelClickAnimation{
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//        [self.userLabel setTextColor:RGB_COLOR(45, 109, 204, 1)];
        self.userLabel.font = [UIFont systemFontOfSize:12];
        self.userLabel.bounds = CGRectMake(0, 0, 80, 15);
        self.userLabel.center = CGPointMake(CGRectGetMaxX(self.userImage.frame)+50, CGRectGetMinY(self.userImage.frame)-15);
    } completion:nil];
}
-(void)userLabelCancelAnimation{
    if ([self.userNameTextField.text isEqualToString:@""]) {
        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
            self.userLabel.bounds = CGRectMake(0, 0, 100, 30);
            self.userLabel.center = CGPointMake(CGRectGetMaxX(self.userImage.frame)+76, CGRectGetMidY(self.userImage.frame));
            self.userLabel.font = [UIFont systemFontOfSize:17];
            [self.userLabel setTextColor:[UIColor whiteColor]];
         
        } completion:nil];
    }
    
}

-(void)passwordClickLabelAnimation{
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//        [self.pswLabel setTextColor:RGB_COLOR(45, 109, 204, 1)];
        self.pswLabel.font = [UIFont systemFontOfSize:12];
        self.pswLabel.bounds = CGRectMake(0, 0, 80, 15);
        self.pswLabel.center = CGPointMake(CGRectGetMaxX(self.lockImage.frame)+50, CGRectGetMinY(self.lockImage.frame)-15);
    } completion:nil];
}
-(void)passwordCancelLabelAnimation{
    if ([self.passwordTextField.text isEqualToString:@""]) {
        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
            self.pswLabel.bounds = CGRectMake(0, 0, 100, 30);
            self.pswLabel.center = CGPointMake(CGRectGetMaxX(self.lockImage.frame)+76, CGRectGetMidY(self.lockImage.frame));
            self.pswLabel.font = [UIFont systemFontOfSize:17];
            [self.pswLabel setTextColor:[UIColor whiteColor]];
        } completion:nil];
    }
}
#pragma mark -- UITextFieldDelegate --
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == self.userNameTextField) {
        [self userLabelCancelAnimation];
    }else if (textField == self.passwordTextField){
        [self passwordCancelLabelAnimation];
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField == self.userNameTextField) {
        [self userLabelClickAnimation];
    }else if (textField == self.passwordTextField){
        [self passwordClickLabelAnimation];
    }
}
#pragma mark -- 键盘处理
// 键盘处理
- (void)keyBoardWillAppear:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds) - 100);
}
// 键盘处理
- (void)keyBoardWillHidden:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), [UIScreen mainScreen].bounds.size.height / 2);
}
#pragma mark *** Touches methods ***
 // 收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   
    [self.view endEditing:YES];
}
#pragma mark -- Getter --
//登录
-(UIImageView *)backgroundImg{
    if (!_backgroundImg) {
        _backgroundImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loginBacground1.jpeg"]];
        _backgroundImg.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }
    return _backgroundImg;
}

-(UIButton *)signInBtn{
    if (!_signInBtn) {
        _signInBtn = [[UIButton alloc]init];
        _signInBtn.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 50);
        _signInBtn.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.passwordTextField.frame)+60);
        _signInBtn.alpha = 0;
        [_signInBtn setBackgroundColor:RGB_COLOR(137, 91, 149, 1)];
        [_signInBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_signInBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_signInBtn addTarget:self action:@selector(respondsToSignInButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _signInBtn;
}
//注册
-(UIButton *)signUpBtn{
    if (!_signUpBtn) {
        _signUpBtn = [[UIButton alloc]init];
        _signUpBtn.frame = CGRectMake(0, 0, 75, 25);
        _signUpBtn.center = CGPointMake(50, CGRectGetMaxY(self.view.frame)-40);
        _signUpBtn.alpha = 0;
        [_signUpBtn setBackgroundColor:[UIColor clearColor]];
        [_signUpBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_signUpBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_signUpBtn addTarget:self action:@selector(respondsToSignUpButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _signUpBtn;
}



-(UITextField *)passwordTextField{
    if (!_passwordTextField) {
        _passwordTextField = [[UITextField alloc]init];
        _passwordTextField.frame = CGRectMake(CGRectGetMaxX(self.lockImage.frame)+5, CGRectGetMinY(self.lockImage.frame)-9, CGRectGetWidth(self.view.frame)-137, 50);
        [_passwordTextField setBackgroundColor:[UIColor clearColor]];
        [_passwordTextField setTintColor:[UIColor whiteColor]];
        [_passwordTextField setTextColor:[UIColor whiteColor]];
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.keyboardType = UIKeyboardTypeDefault;
        _passwordTextField.borderStyle = UITextBorderStyleNone;
    }
    return _passwordTextField;
}
-(UIView *)pswView{
    if (!_pswView) {
        _pswView = [[UIView alloc]init];
        _pswView.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 1);
        _pswView.center = CGPointMake(CGRectGetMaxX(self.view.frame)*3/2-50, CGRectGetMaxY(self.passwordTextField.frame));
        _pswView.backgroundColor = [UIColor whiteColor];
        
    }
    return _pswView;
}
-(UIImageView *)lockImage{
    if (!_lockImage) {
        _lockImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Password.png"]];
        _lockImage.bounds = CGRectMake(0, 0, 32, 32);
        _lockImage.center = CGPointMake(CGRectGetMidX(self.userImage.frame), CGRectGetMidY(self.userImage.frame)+65);
        _lockImage.alpha = 0;
    }
    return _lockImage;
}
-(UILabel *)pswLabel{
    if (!_pswLabel) {
        _pswLabel = [[UILabel alloc]init];
        _pswLabel.bounds = CGRectMake(0, 0, 100, 30);
        _pswLabel.center = CGPointMake(CGRectGetMaxX(self.view.frame)+50, CGRectGetMidY(self.lockImage.frame));
        _pswLabel.text = @"请输入密码";
        [_pswLabel setTextColor:[UIColor whiteColor]];
    }
    return _pswLabel;
}



-(UITextField *)userNameTextField{
    if (!_userNameTextField) {
        _userNameTextField = [[UITextField alloc]init];
        _userNameTextField.frame = CGRectMake(CGRectGetMaxX(self.userImage.frame)+5, CGRectGetMinY(self.userImage.frame)-9, CGRectGetWidth(self.view.frame)-137, 50);
        [_userNameTextField setBackgroundColor:[UIColor clearColor]];
        [_userNameTextField setTintColor:[UIColor whiteColor]];
        [_userNameTextField setTextColor:[UIColor whiteColor]];
        _userNameTextField.secureTextEntry = NO;
        _userNameTextField.keyboardType = UIKeyboardTypeDefault;
        _userNameTextField.borderStyle = UITextBorderStyleNone;
    }
    return _userNameTextField;
}
-(UIView *)userView{
    if (!_userView) {
        _userView = [[UIView alloc]init];
        _userView.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-100, 1);
        _userView.center = CGPointMake(CGRectGetMaxX(self.view.frame)*3/2-50, CGRectGetMaxY(self.userNameTextField.frame));
        _userView.backgroundColor = [UIColor whiteColor];
    }
    return _userView;
}
-(UIImageView *)userImage{
    if (!_userImage) {
        _userImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"User.png"]];
        _userImage.frame = CGRectMake(50, CGRectGetMidY(self.view.frame), 32, 32);
        _userImage.alpha = 0;
    }
    return _userImage;
}
-(UILabel *)userLabel{
    if (!_userLabel) {
        _userLabel = [[UILabel alloc]init];
        _userLabel.bounds = CGRectMake(0, 0, 100, 30);
        _userLabel.center = CGPointMake(CGRectGetMaxX(self.view.frame)+50, CGRectGetMidY(self.userImage.frame));
        _userLabel.text = @"请输入账号";
        [_userLabel setTextColor:[UIColor whiteColor]];
    }
    return _userLabel;
}

-(UIButton *)findPswBtn{
    if (!_findPswBtn) {
        _findPswBtn = [[UIButton alloc]init];
        _findPswBtn.frame = CGRectMake(0, 0, 90, 25);
        _findPswBtn.center = CGPointMake(CGRectGetMaxX(self.view.frame)-60, CGRectGetMaxY(self.view.frame)-40);
        _findPswBtn.alpha = 0;
        [_findPswBtn setBackgroundColor:[UIColor clearColor]];
        [_findPswBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
        [_findPswBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_findPswBtn addTarget:self action:@selector(respondsToSignUpButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _findPswBtn;
}
@end
